package service;

import java.io.IOException;
import java.util.ArrayList;

import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.util.Duration;
import adapter.HTTPSiloAdapter;
import adapter.SiloAdapter;
import data.Silo;
import data.SiloState;

public class SiloService extends ScheduledService<ArrayList<Silo>> {

	private int numberOfSilos;
	private ArrayList<HTTPSiloAdapter> siloAdapters = new ArrayList<HTTPSiloAdapter>();

	public SiloService() {
		super.setPeriod(Duration.seconds(3));
	}

	public void createSiloAdapter(String iNetAdress, String port) {
		siloAdapters.add(new HTTPSiloAdapter(iNetAdress, port));
	}

	public int getNumberOfSilos() {
		return numberOfSilos;
	}

	public void setNumberOfSilos(int numberOfSilos) {

		this.numberOfSilos = numberOfSilos;
	}

	@Override
	protected Task<ArrayList<Silo>> createTask() {
		return new Task<ArrayList<Silo>>() {

			@Override
			protected ArrayList<Silo> call() throws Exception {
				ArrayList<Silo> result = new ArrayList<Silo>();

				for (SiloAdapter siloAdpter : siloAdapters) {
					ArrayList<String[]> currentSiloData = siloAdpter
							.requestCurrentSiloData();

					if (siloAdpter.getRegistratedSilos().size() == currentSiloData
							.size()) {
						for (String[] data : currentSiloData) {

							updateSilos(
									data[1],
									siloAdpter.getRegistratedSilos().get(
											Integer.parseInt(data[0])));

						}
						result.addAll(siloAdpter.getRegistratedSilos());
					}
				}
				return result;
			}

		};

	}

	public void updateSilos(String data, Silo silo) {

		switch (data) {
		case "inf":
			silo.setCurrent(silo.getMax());
			silo.setState(SiloState.HIGH);
			break;
		case "-inf":
			silo.setCurrent(silo.getMin());
			silo.setState(SiloState.LOW);
			break;
		case "nan":
			silo.setState(SiloState.ERROR);
			break;
		default:
			silo.setCurrent(Double.parseDouble(data));
		}

	}

	public void requestInitialSiloData() throws IOException {
		for (HTTPSiloAdapter siloAdapter : siloAdapters) {
			createSilos(siloAdapter.requestSourceSiloData(), siloAdapter);
		}

	}

	private void createSilos(ArrayList<String[]> data,
			HTTPSiloAdapter siloAdapter) {
		for (String[] siloData : data) {
			Silo silo = new Silo(siloData[1], Double.parseDouble(siloData[8]),
					Double.parseDouble(siloData[9]), siloData[3], siloAdapter);
			siloAdapter.getRegistratedSilos().add(silo);
		}

	}

	public ArrayList<HTTPSiloAdapter> getSiloAdapters() {
		return siloAdapters;
	}

}
